import { getRoutes } from '@/api/system/role'
import { asyncRoutes, constantRoutes } from '@/router'
import Layout from '@/layout'


/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
    if (route.meta && route.meta.roles) {
        return roles.some(role => route.meta.roles.includes(role))
    } else {
        return true
    }
}

// const loadView = (view) => {
//     if (process.env.NODE_ENV === 'development') {
//       return (resolve) => require([`@/views/${view}`], resolve)
//     } else {
//       // 使用 import 实现生产环境的路由懒加载
//       return () => import(`@/views/${view}`)
//     }
//   }

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
    const res = []

    routes.forEach(route => {
        const tmp = { ...route }
        if (tmp.component === 'Layout') {
            tmp.component = Layout
        } else {
            const view = tmp.component
            // tmp.component = () => import(`@/views/${view_str}`)
            tmp.component = (resolve) => require([`@/views/${view}`], resolve)

        }

        if (hasPermission(roles, tmp)) {
            if (tmp.children) {
                tmp.children = filterAsyncRoutes(tmp.children, roles)
            }
            res.push(tmp)
        }
    })

    return res
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    }
}

const actions = {
    generateRoutes({ commit }, roles) {
        return new Promise(resolve => {

            // let accessedRoutes
            // if (roles.includes('admin')) {
            //     accessedRoutes = asyncRoutes || []
            // } else {
            //     accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
            // }
            getRoutes(roles).then(res => {
                let accessedRoutes = filterAsyncRoutes(res.data, roles)
                commit('SET_ROUTES', accessedRoutes)
                resolve(accessedRoutes)
            }).catch(err => {
                console.log(err)
            })
            // console.log('accessedRoutes:', tmpRouters)
            // commit('SET_ROUTES', accessedRoutes)
            // resolve(accessedRoutes)

            // console.log(roles)
            // 修改从后端获取路由
            // getRoutes({ commit }, roles).then(res => {
            // console.log('res:', res)
            //  accessedRoutes = res.data
            // })
        })
    }
}


export default {
    namespaced: true,
    state,
    mutations,
    actions
}
